<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout :formInfos="q_formInfos" :formDatas="q_formDatas" message="" @onFind="onFind"></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn
          :addData="true"
          @onAddData="onAddData"
          :delectData="true"
          @onDelectData="onDelectData"
        >
          <template #cusBtn>
            <!-- <export-excel ref="export" @getExcelData="onExportData"></export-excel> -->
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{ y: slotData.tableHeight }"
          :tagClicks3="['licenceMaster']"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          @onTouchCell="onTouchCell"
          @onTouchTagCell="onTouchTagCell"
        >
        </a-list-table>
      </template>
    </table-layout>
    <addModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
    <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
    <add-seller-lic-modal ref="addSellerLicModal" @onSaveModal="onSaveModal" /> 
    <import-excel ref="import" @onSubmit="onSubmitExcel" />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import addModal from './manufacturerModal'
import viewModal from './viewModal'
import addSellerLicModal from './addSellerLicModal'
import exportExcel from '@/views/app/biz/common/exportExcel/index'
import importExcel from '@/views/app/biz/common/importExcel'
import { getByConditions, getByConditionsCount, deleteInfo } from './manufacturer'
import {columns,q_formInfos,q_formDatas } from './dataConfig'


export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    exportExcel,
    addModal,
    addSellerLicModal,
    viewModal,
    importExcel,
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100']
      },
      q_formInfos: q_formInfos,
      q_formDatas: q_formDatas,
      pData: {}, // 条件查询参数
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {},

  created() {
    this.getTotal()
    this.getList(this.q_formDatas)
  },
  methods: {
    formatParms(){
      let sbdata=JSON.parse(JSON.stringify(this.q_formDatas))
      for (let key in sbdata) {
        // console.log(key,sbdata[key]);
        if (!sbdata[key]){
          sbdata[key]=null  
        }
        if (key=='manufacturerZh') {
          if (sbdata[key]==null) {
            sbdata[key]=`%%`
          }else{
            sbdata[key]=`%${sbdata[key]}%`
          }
          
        }
      }
      return sbdata
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.formatParms())
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = showTotal => {
          return `共 ${showTotal} 条`
        }
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', this.formatParms())
      this.loading = true
      this.listdata = []
      let res = ''
      res = await getByConditions(this.formatParms(), this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let item of resdata) {
          this.listdata.push({
            key: item.pid,
            action: ['编辑', '删除'],
            ...item
          })
        }
      } else {
        this.listdata = []
      }
      console.log(this.listdata);
      this.loading = false
    },
    // 新增按钮 点击了新增
    onAddData() {
      console.log('点击了新增')
      // this.$refs.modal.addModal()
      this.$router.push({
        name:'addManufacturer',
        params:{
          isJump:false,
          pathName:this.$route.name,
          pid:null,
          type:'add'
        }
      })
    },
    // 关闭模态详细框
    handleModalCancel() {},
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      console.log('点击list中的操作按钮', text, record, index)
      if (text == '编辑') {
        //编辑
        // this.$refs.modal.editModal(record.pid)
        this.$router.push({
          name: 'addManufacturer',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:record.pid,
            type:'edit'
          } 
        })
      } else if (text == '删除') {
        this.showConfirm(record, '1')
      }
    },
    showConfirm(val, type) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.pushGoods(item))
          }
          return Promise.all(reqArr)
            .then(res => {
              console.log(res)
              for (const item of res) {
                console.log(item)
                if (item && item.code && item.code === 'C1' && item.data) {
                  that.$message.success({ content: '商品' + item.data.productNameZh + '删除成功', duration: 3 })
                } else {
                  that.$message.error({
                    content: '商品' + item.data.productNameZh + '删除失败，原因：' + item.message,
                    duration: 3
                  })
                }
              }
              that.handleModalSaveOk()
            })
            .catch(err => {
              that.$message.error({ content: '操作出错:' + err, duration: 3 })
            })
        },
        onCancel() {}
      })
    },
    async pushGoods(val) {
      let res = await deleteInfo(val)
      return res
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind() {
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    onSaveModal(){
      this.getList(this.q_formDatas)
    },
    onTouchCell(text, record, index) {
      this.$refs.viewModal.showModal(record.pid, record)
    },
    onTouchTagCell(text, record, index,col){
      if(col=='licenceMaster'){
        console.log('点击了生产企业主证照的tag:',col,record);
        if(text){
          //点击了生产企业主证照上传的tag
          this.$refs.addSellerLicModal.addModal(record.pid)
        }else{
          //点击了生产企业主证照查看的tag
          this.$refs.addSellerLicModal.editModal(record.pid)
        }
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onDelectData() {
      if (this.selectedRows.length) {
        this.showConfirm(this.selectedRows)
      } else {
        this.$message.warning({ content: '未选择要删除的商品', duration: 3 })
      }
    },
    //提交导入数据
    async onSubmitExcel(val) {
      console.log(val)
      //执行提交数据代码，提交成功后执行this.$refs.import.closeModal2()
      let key = 'updatable'
      this.$message.loading({ content: '正在导入中', key })
      // let res = await saveInfo(val)
      let res = { code: 'C1', data: [] }
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '导入成功', key, duration: 3 })
        this.$refs.import.closeModal2()
        this.getList(this.q_formDatas)
      } else {
        this.$message.error({ content: '导入失败,请稍后再试', key, duration: 3 })
      }
    },
    //点击导出数据
    onExportData() {
      //如需请求数据，则在此请求数据后执行以下
      let listName = '基础商品信息'
      let listHeader = [
        '商品自编码',
        '商品名称',
        '一级分类（学科、品类）',
        '二级分类（用途、品目）',
        '三级分类（部位、功能、品种）',
        '品牌'
      ]
      let listField = ['code', 'productNameZh', 'first', 'second', 'third', 'brand']
      let exportList = this.listdata
      this.$refs.export.setData(listName, listHeader, listField, exportList)
    }
  }
}
</script>

<style></style>
